package com.xz.framework.interceptor;


import com.xz.common.core.domain.entity.SysTenant;
import com.xz.common.core.domain.model.LoginUser;
import com.xz.common.exception.ServiceException;
import com.xz.tenant.TenantContext;
import com.xz.framework.web.service.TokenService;
import com.xz.system.service.ISysTenantService;
import com.xz.tenant.TenantConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public  class TenantSetInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysTenantService sysTenantService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURL = request.getRequestURI();
        if(requestURL.contains("/outSign/signSms")||requestURL.contains("/outSign/sign")||requestURL.contains("/api/")||requestURL.contains("/deduction/log/getInfo")
        ||requestURL.contains("/outSign/unsign")
        ||requestURL.contains("/deduction/order/pay")
        ||requestURL.contains("/deduction/order/deductionCallback")
        ||requestURL.contains("/deduction/alt/order/altCallback")
        ||requestURL.contains("/car/altAuthNotify")
        ||requestURL.contains("/car/altImageApproveNotify")
        ||requestURL.contains("/common/verifyCode")
        ||requestURL.contains("/common/updatePwd")
        ){
          TenantContext.setOutFlag("1");
           return  true;
        }
        if(requestURL.contains("swagger")||requestURL.contains("doc.html")||requestURL.contains("webjars")){
            return  true;
        }
        LoginUser loginUser = tokenService.getLoginUser(request);
        if(loginUser==null){
            return true;
        }
        SysTenant sysTenant = sysTenantService.getById(loginUser.getTenantId());
        if(null == sysTenant || sysTenant.getDelFlag().equals(TenantConstant.DELETE_STATUS)){
            throw new ServiceException("商户不存在!");
        }
        if(sysTenant.getTenantFlag().equals(TenantConstant.DISABLE_STATUS)){
            throw new ServiceException("商户已禁用!");
        }
        TenantContext.setSysTenantThreadLocal(sysTenant);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        TenantContext.removeSysTenantThreadLocal();
        TenantContext.removeOutFlag();
    }
}
